<template>
  <div class="container">
    <el-card>
      <div class="header-box" v-if="this.objPage.subjectID">
        <el-breadcrumb separator-class="el-icon-arrow-right" class="box">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ tagName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-row style="display: flex;justify-content: space-between">
        <el-col :span="16"
          ><div class="grid-content bg-purple">
            <el-form
              :inline="true"
              ref="form"
              :model="formInline"
              class="demo-form-inline"
            >
              <el-form-item label="标签名称">
                <el-input v-model.trim="formInline.tagName"></el-input>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="formInline.state" placeholder="请选择">
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="btnClearContext">清除</el-button>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
          </div></el-col
        >
        <el-col :span="6"
          ><div
            class="grid-content bg-purple-light"
            style="text-align: right;line-height: 83px;"
          >
            <!-- 返回学科 -->
            <el-link
              v-if="this.objPage.subjectID"
              class="directorys-link"
              type="primary"
              size="small"
              @click="$router.back()"
              :underline="false"
              icon="el-icon-back"
              >返回学科</el-link
            >
            <el-button
              type="success"
              icon="el-icon-edit"
              @click="addTagDialog"
              style="margin-left: 10px;"
              >新增标签</el-button
            >
          </div></el-col
        >
      </el-row>

      <!-- 消息提示 -->
      <div class="messagePrompt">
        <i class="el-icon-info"></i>
        <span class="content">一共有{{ counts }}条</span>
      </div>
      <!-- <el-alert title="一共有N条" type="info" show-icon> </el-alert> -->
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
        <el-table-column prop="tagName" label="标签名称"> </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column label="创建日期">
          <!-- 作用域插槽 -->
          <template v-slot="scope">
            {{ scope.row.addDate | formdate }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.state === 1 ? '已启用' : '已禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              :underline="false"
              @click="BtnEnable(scope.row)"
              >{{ scope.row.state === 1 ? '禁用' : '启用' }}</el-button
            >
            <el-button
              type="text"
              :underline="false"
              @click="toAddEdit(scope.row)"
              :disabled="scope.row.state === 1 ? false : true"
              >修改</el-button
            >
            <el-button
              type="text"
              :underline="false"
              @click="addDelete(scope.row)"
              :disabled="scope.row.state === 1 ? false : true"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        style="text-align: right"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="objPage.page"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="objPage.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>
    <!-- 新增目录对话框 -->
    <el-dialog
      :title="isEdit ? '编辑标签' : '新增标签'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="所属学科" prop="subjectID" v-if="!tagName">
          <el-select v-model="form.subjectID" placeholder="请选择">
            <el-option
              v-for="item in simpleList"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="tagName">
          <el-input v-model.trim="form.tagName" style="width: 218px"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { list, add, remove, update, changeState } from '@/api/hmmm/tags'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      simpleList: [],
      userId: '',
      formInline: {
        tagName: '',
        state: ''
      },
      // // 分页
      // objPage: {
      //   page: 1, // 页码值
      //   pagesize: 10 // 每页显示的条数
      // },
      // 对话框表单
      form: {
        subjectID: '',
        tagName: '',
        id: '',
        subjectName: ''
      },
      counts: 0,
      // 页面数据列表
      tableData: [],
      dialogVisible: false, // 判断是否展示对话框
      rules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'blur' }
        ],
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      },
      // 判断是否展示编辑还是添加对话框
      isEdit: false,
      isShow: false, // 按钮显示与隐藏
      flag: false // 按钮是否禁用
    }
  },
  created () {
    this.getSimple()
    console.log(this.tagName)
    this.getTagList()
  },
  computed: {
    ...mapState('route', ['objPage', 'tagName'])
  },
  methods: {
    // 获取学科列表
    async getSimple () {
      const res = await simple()
      this.simpleList = res.data
    },
    goBack () {
      console.log('go back')
    },
    // 渲染列表
    async getTagList () {
      const res = await list(this.objPage)
      // console.log(res, 99999)
      this.tableData = res.data.items
      this.counts = res.data.counts
    },
    btnClearContext () {
      this.formInline = {
        tagName: '',
        state: ''
      }
    },
    // 查询功能
    async onSubmit () {
      const res = await list({
        ...this.objPage,
        ...this.formInline
      })
      // 筛选标签类别中的数据
      this.tableData = res.data.items
      this.counts = res.data.counts
    },
    // 当前页数
    handleSizeChange (val) {
      this.objPage.pagesize = val
      this.getTagList()
      // console.log(`每页 ${val} 条`)
    },
    // 页码
    handleCurrentChange (val) {
      this.objPage.page = val
      this.getTagList()
    },
    // 点击添加按钮
    addTagDialog () {
      // if (this.tagName) {
      //   this.isEdit = false
      //   this.dialogVisible = true
      //   this.form = {
      //     subjectID: '',
      //     tagName: this.tagName,
      //     id: '',
      //     subjectName: ''
      //   }
      // } else {
      this.isEdit = false
      this.dialogVisible = true
      this.form = {
        subjectID: '',
        tagName: '',
        id: '',
        subjectName: ''
      }
    },
    // 三元表达式判断，是否点击修改或编辑功能
    addOrEdit () {
      this.isEdit ? this.toEdit() : this.toAddTags()
    },
    // 关闭对话框
    handleClose (done) {
      this.dialogVisible = false
    },
    // 添加tag对话框
    async toAddTags () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.tagName) {
            this.form.subjectID = parseInt(this.objPage.subjectID)
            await add(this.form)
            this.$message({
              showClose: true,
              message: '恭喜你，标签添加成功',
              type: 'success'
            })
            this.dialogVisible = false
            this.form = {
              subjectID: '',
              tagName: '',
              id: '',
              subjectName: ''
            }
            this.getTagList()
          } else {
            await add(this.form)
            this.$message({
              showClose: true,
              message: '恭喜你，标签添加成功',
              type: 'success'
            })
            this.dialogVisible = false
            this.form = {
              subjectID: '',
              tagName: '',
              id: '',
              subjectName: ''
            }
            this.getTagList()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除功能
    addDelete (row) {
      this.$confirm('请确定是否需要删除标签?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          //  总页数
          // Math.ceil返回最小整数
          const totalPage = Math.ceil((this.counts - 1) / this.objPage.pagesize)
          this.objPage.page =
            this.objPage.page > totalPage ? totalPage : this.objPage.page
          this.objPage.page = this.objPage.page < 1 ? 1 : this.objPage.page

          this.getTagList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 修改学科
    toAddEdit (row) {
      console.log(row, 88888)
      this.isEdit = true
      this.dialogVisible = true
      // 把值渲染到编辑弹框中
      // 深拷贝，修改页面时不影响表格列表数据，避免修改同时列表数据跟随修改
      this.form = JSON.parse(JSON.stringify(row))
    },
    // 点击确定之后的操作~
    toEdit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 编辑成功
          await update(this.form)
          this.$message({
            showClose: true,
            message: '恭喜你，标签修改成功',
            type: 'success'
          })
          // 关闭对话框
          this.dialogVisible = false
          // 清空表单
          this.form = {
            subjectID: '',
            tagName: '',
            id: '',
            subjectName: ''
          }
          // 重置验证
          this.$refs.form.resetFields()
          // 刷新列表
          this.getTagList()
          this.getTagList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 思路分析
    // 启用按钮
    // 1、点击启用按钮，启用按钮隐藏，禁用按钮显示
    // 2、届时修改、删除按钮隐藏,颜色变成灰色
    // 3、列表中的状态发生变化，已禁用==》已启用
    // 禁用按钮
    // 1、点击禁用按钮，禁用按钮隐藏，启用按钮显示
    // 2、届时修改、删除按钮显示，颜色变成色
    // 3、列表中的状态跟随发生变化，已启用===》已禁用
    async BtnEnable (row) {
      row.state === 1 ? (row.state = 0) : (row.state = 1)
      await changeState({
        id: row.id,
        state: row.state
      })
      this.flag = !this.flag
    }
  }
}
</script>

<style lang="scss">
.container {
  padding: 10px 20px 20px 20px;
}
.header-box {
  width: 100%;
  height: 40px;
  // border-bottom: 1px solid #ebeef5;
  padding-top: 10px;
  margin-bottom: 20px;
}

.messagePrompt {
  background-color: #f4f4f5;
  color: #909399;
  padding: 8px 16px;
  margin-bottom: 15px;
  .content {
    padding: 0 8px;
  }
}
.box {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 15px;
}
.el-form {
  margin-top: 25px;
}
</style>
